package net.csdn.business.notify.common.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.csdn.business.notify.common.constant.CommonConstants;
import net.csdn.business.notify.common.enums.ResultCodeEnum;
import net.csdn.business.notify.common.exception.ApiErrorResult;
import org.slf4j.MDC;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Collections;

/**
 * @author likun
 * @date 2022/12/9 14:04
 */
public class ResponseResultUtil {
    private static MultiValueMap<String, String> buildCustomHeader() {
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.put(CommonConstants.FIELD_TRACE_ID, Collections.singletonList(MDC.get(CommonConstants.TRACE_ID)));
        return header;
    }

    public static ResponseEntity<ApiErrorResult> buildErrorResponse(ResultCodeEnum resultCode) {
        return new ResponseEntity<>(new ApiErrorResult(resultCode), resultCode.getHttpStatus());
    }

    public static ResponseEntity<ApiErrorResult> buildErrorResponse(String errorCodeName, String message) {
        ResultCodeEnum resultCode = ResultCodeEnum.getResultCode(errorCodeName);
        return new ResponseEntity<>(new ApiErrorResult(resultCode.name(), resultCode.getCode(), message), resultCode.getHttpStatus());
    }

    public static ResponseEntity<ApiErrorResult> buildErrorResponse(ResultCodeEnum resultCode, String message) {
        return new ResponseEntity<>(new ApiErrorResult(resultCode.name(), resultCode.getCode(), message), resultCode.getHttpStatus());
    }

    public static ResponseEntity<ApiErrorResult> buildErrorResponse(int code, String errorCodeName, String message) {
        ResultCodeEnum resultCode = ResultCodeEnum.getResultCode(errorCodeName);
        return new ResponseEntity<>(new ApiErrorResult(resultCode.name(), code, message), resultCode.getHttpStatus());
    }

    public static String serializeErrorResult(ApiErrorResult result) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException ignore) {

        }
        return JSON.toJSONString(result,JSONWriter.Feature.WriteNulls);
    }
}